// 全局状态管理
const state = {
    mode: 'custom', // 'custom' 或 'template'
    currentTemplate: 'gradient1',
    backgroundImage: null,
    aspectRatio: '16:9',
    canvas: null,
    ctx: null
};

// 模板配置
const templates = {
    gradient1: {
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        textColor: '#ffffff',
        overlay: true
    },
    gradient2: {
        background: 'linear-gradient(135deg, #2193b0 0%, #6dd5ed 100%)',
        textColor: '#ffffff',
        overlay: true
    },
    gradient3: {
        background: 'linear-gradient(135deg, #ee9ca7 0%, #ffdde1 100%)',
        textColor: '#333333',
        overlay: false
    },
    tech: {
        background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
        textColor: '#00ff88',
        overlay: true
    },
    minimal: {
        background: 'linear-gradient(135deg, #ffffff 0%, #f0f0f0 100%)',
        textColor: '#333333',
        overlay: false
    },
    nature: {
        background: 'linear-gradient(135deg, #56ab2f 0%, #a8e063 100%)',
        textColor: '#ffffff',
        overlay: true
    }
};

// 比例配置
const aspectRatios = {
    '16:9': { width: 1200, height: 675 },
    '4:3': { width: 1200, height: 900 },
    '3:2': { width: 1200, height: 800 },
    '1:1': { width: 1200, height: 1200 },
    '21:9': { width: 1200, height: 514 }
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initCanvas();
    initEventListeners();
    drawCover();
});

// 初始化Canvas
function initCanvas() {
    state.canvas = document.getElementById('coverCanvas');
    state.ctx = state.canvas.getContext('2d');
    updateCanvasSize();
}

// 更新Canvas尺寸
function updateCanvasSize() {
    const ratio = aspectRatios[state.aspectRatio];
    state.canvas.width = ratio.width;
    state.canvas.height = ratio.height;
}

// 初始化事件监听
function initEventListeners() {
    // 模式切换
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.mode = btn.dataset.mode;
            switchMode(state.mode);
        });
    });

    // 自定义模式控件
    document.getElementById('bgImageInput').addEventListener('change', handleImageUpload);
    document.getElementById('aspectRatio').addEventListener('change', (e) => {
        state.aspectRatio = e.target.value;
        updateCanvasSize();
        drawCover();
    });
    document.getElementById('titleText').addEventListener('input', drawCover);
    document.getElementById('subtitleText').addEventListener('input', drawCover);
    document.getElementById('textColor').addEventListener('input', drawCover);
    document.getElementById('titleSize').addEventListener('input', (e) => {
        document.getElementById('titleSizeValue').textContent = e.target.value + 'px';
        drawCover();
    });
    document.getElementById('subtitleSize').addEventListener('input', (e) => {
        document.getElementById('subtitleSizeValue').textContent = e.target.value + 'px';
        drawCover();
    });
    document.getElementById('titleBold').addEventListener('change', drawCover);
    document.getElementById('titleItalic').addEventListener('change', drawCover);
    document.getElementById('fontFamily').addEventListener('change', drawCover);
    document.getElementById('overlayOpacity').addEventListener('input', (e) => {
        document.getElementById('overlayOpacityValue').textContent = e.target.value + '%';
        drawCover();
    });
    document.getElementById('textPosition').addEventListener('change', drawCover);

    // 模板模式控件
    document.querySelectorAll('.template-item').forEach(item => {
        item.addEventListener('click', () => {
            document.querySelectorAll('.template-item').forEach(i => i.classList.remove('selected'));
            item.classList.add('selected');
            state.currentTemplate = item.dataset.template;
            drawCover();
        });
    });
    document.getElementById('templateAspectRatio').addEventListener('change', (e) => {
        state.aspectRatio = e.target.value;
        updateCanvasSize();
        drawCover();
    });
    document.getElementById('templateTitleText').addEventListener('input', drawCover);
    document.getElementById('templateSubtitleText').addEventListener('input', drawCover);
    document.getElementById('templateTitleSize').addEventListener('input', (e) => {
        document.getElementById('templateTitleSizeValue').textContent = e.target.value + 'px';
        drawCover();
    });
    document.getElementById('templateSubtitleSize').addEventListener('input', (e) => {
        document.getElementById('templateSubtitleSizeValue').textContent = e.target.value + 'px';
        drawCover();
    });
    document.getElementById('templateTitleBold').addEventListener('change', drawCover);
    document.getElementById('templateTitleItalic').addEventListener('change', drawCover);

    // 操作按钮
    document.getElementById('downloadBtn').addEventListener('click', downloadCover);
    document.getElementById('resetBtn').addEventListener('click', resetAll);

    // 默认选中第一个模板
    document.querySelector('.template-item').classList.add('selected');
}

// 切换模式
function switchMode(mode) {
    if (mode === 'custom') {
        document.getElementById('custom-controls').classList.remove('hidden');
        document.getElementById('template-controls').classList.add('hidden');
    } else {
        document.getElementById('custom-controls').classList.add('hidden');
        document.getElementById('template-controls').classList.remove('hidden');
    }
    drawCover();
}

// 处理图片上传
function handleImageUpload(e) {
    const file = e.target.files[0];
    if (file && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = (event) => {
            const img = new Image();
            img.onload = () => {
                state.backgroundImage = img;
                drawCover();
            };
            img.src = event.target.result;
        };
        reader.readAsDataURL(file);
    }
}

// 绘制封面
function drawCover() {
    const ctx = state.ctx;
    const canvas = state.canvas;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (state.mode === 'custom') {
        drawCustomCover();
    } else {
        drawTemplateCover();
    }
}

// 绘制自定义封面
function drawCustomCover() {
    const ctx = state.ctx;
    const canvas = state.canvas;

    // 绘制背景
    if (state.backgroundImage) {
        // 绘制图片背景（覆盖整个画布）
        const imgRatio = state.backgroundImage.width / state.backgroundImage.height;
        const canvasRatio = canvas.width / canvas.height;
        
        let drawWidth, drawHeight, offsetX = 0, offsetY = 0;
        
        if (imgRatio > canvasRatio) {
            // 图片更宽，以高度为准
            drawHeight = canvas.height;
            drawWidth = drawHeight * imgRatio;
            offsetX = (canvas.width - drawWidth) / 2;
        } else {
            // 图片更高，以宽度为准
            drawWidth = canvas.width;
            drawHeight = drawWidth / imgRatio;
            offsetY = (canvas.height - drawHeight) / 2;
        }
        
        ctx.drawImage(state.backgroundImage, offsetX, offsetY, drawWidth, drawHeight);
        
        // 添加遮罩
        const opacity = document.getElementById('overlayOpacity').value / 100;
        ctx.fillStyle = `rgba(0, 0, 0, ${opacity})`;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    } else {
        // 默认渐变背景
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, '#667eea');
        gradient.addColorStop(1, '#764ba2');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    // 绘制文字
    const titleText = document.getElementById('titleText').value || '请输入标题';
    const subtitleText = document.getElementById('subtitleText').value;
    const textColor = document.getElementById('textColor').value;
    const titleSize = parseInt(document.getElementById('titleSize').value);
    const subtitleSize = parseInt(document.getElementById('subtitleSize').value);
    const fontFamily = document.getElementById('fontFamily').value;
    const position = document.getElementById('textPosition').value;
    const isBold = document.getElementById('titleBold').checked;
    const isItalic = document.getElementById('titleItalic').checked;

    drawText(titleText, subtitleText, textColor, titleSize, subtitleSize, fontFamily, position, isBold, isItalic);
}

// 绘制模板封面
function drawTemplateCover() {
    const ctx = state.ctx;
    const canvas = state.canvas;
    const template = templates[state.currentTemplate];

    // 绘制渐变背景
    const gradient = parseGradient(template.background);
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 添加图案/装饰
    if (template.overlay) {
        drawTemplatePattern(state.currentTemplate);
    }

    // 绘制文字
    const titleText = document.getElementById('templateTitleText').value || '请输入标题';
    const subtitleText = document.getElementById('templateSubtitleText').value;
    const titleSize = parseInt(document.getElementById('templateTitleSize').value);
    const subtitleSize = parseInt(document.getElementById('templateSubtitleSize').value);
    const isBold = document.getElementById('templateTitleBold').checked;
    const isItalic = document.getElementById('templateTitleItalic').checked;
    
    drawText(titleText, subtitleText, template.textColor, titleSize, subtitleSize, "'Microsoft YaHei', sans-serif", 'center', isBold, isItalic);
}

// 解析渐变字符串为Canvas渐变
function parseGradient(gradientStr) {
    const ctx = state.ctx;
    const canvas = state.canvas;
    
    // 提取颜色值
    const colors = gradientStr.match(/#[0-9a-fA-F]{6}/g);
    
    if (colors && colors.length >= 2) {
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, colors[0]);
        gradient.addColorStop(1, colors[1]);
        return gradient;
    }
    
    return '#667eea'; // 默认颜色
}

// 绘制模板图案
function drawTemplatePattern(templateName) {
    const ctx = state.ctx;
    const canvas = state.canvas;
    
    ctx.save();
    ctx.globalAlpha = 0.1;
    
    // 根据不同模板绘制不同图案
    switch(templateName) {
        case 'tech':
            // 科技风：网格
            ctx.strokeStyle = '#00ff88';
            ctx.lineWidth = 2;
            for (let i = 0; i < canvas.width; i += 50) {
                ctx.beginPath();
                ctx.moveTo(i, 0);
                ctx.lineTo(i, canvas.height);
                ctx.stroke();
            }
            for (let i = 0; i < canvas.height; i += 50) {
                ctx.beginPath();
                ctx.moveTo(0, i);
                ctx.lineTo(canvas.width, i);
                ctx.stroke();
            }
            break;
        case 'nature':
            // 自然风：圆点
            ctx.fillStyle = '#ffffff';
            for (let i = 0; i < 20; i++) {
                const x = Math.random() * canvas.width;
                const y = Math.random() * canvas.height;
                const r = Math.random() * 30 + 10;
                ctx.beginPath();
                ctx.arc(x, y, r, 0, Math.PI * 2);
                ctx.fill();
            }
            break;
    }
    
    ctx.restore();
}

// 绘制文字
function drawText(title, subtitle, color, titleSize, subtitleSize, font, position, isBold, isItalic) {
    const ctx = state.ctx;
    const canvas = state.canvas;

    ctx.fillStyle = color;
    ctx.textAlign = 'center';

    // 计算文字位置
    let x = canvas.width / 2;
    let y = canvas.height / 2;

    switch(position) {
        case 'top':
            y = canvas.height * 0.25;
            break;
        case 'bottom':
            y = canvas.height * 0.75;
            break;
        case 'left':
            x = canvas.width * 0.25;
            ctx.textAlign = 'left';
            break;
        case 'right':
            x = canvas.width * 0.75;
            ctx.textAlign = 'right';
            break;
    }

    // 构建字体样式
    let fontStyle = '';
    if (isItalic) fontStyle += 'italic ';
    if (isBold) fontStyle += 'bold ';
    
    // 绘制标题
    ctx.font = `${fontStyle}${titleSize}px ${font}`;
    
    // 添加文字阴影提高可读性
    ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
    ctx.shadowBlur = 10;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    
    // 自动换行
    const maxWidth = canvas.width * 0.8;
    const lines = wrapText(ctx, title, maxWidth);
    
    lines.forEach((line, index) => {
        const lineY = y + (index - (lines.length - 1) / 2) * (titleSize * 1.2);
        ctx.fillText(line, x, lineY);
    });

    // 绘制副标题
    if (subtitle) {
        // 副标题使用普通字体样式（不加粗）
        let subtitleFontStyle = '';
        if (isItalic) subtitleFontStyle += 'italic ';
        ctx.font = `${subtitleFontStyle}${subtitleSize}px ${font}`;
        const subtitleY = y + lines.length * titleSize * 0.6 + 30;
        
        const subtitleLines = wrapText(ctx, subtitle, maxWidth);
        subtitleLines.forEach((line, index) => {
            const lineY = subtitleY + index * (subtitleSize * 1.2);
            ctx.fillText(line, x, lineY);
        });
    }
    
    // 重置阴影
    ctx.shadowColor = 'transparent';
}

// 文字自动换行
function wrapText(ctx, text, maxWidth) {
    const words = text.split('');
    const lines = [];
    let currentLine = '';

    for (let i = 0; i < words.length; i++) {
        const testLine = currentLine + words[i];
        const metrics = ctx.measureText(testLine);
        
        if (metrics.width > maxWidth && currentLine !== '') {
            lines.push(currentLine);
            currentLine = words[i];
        } else {
            currentLine = testLine;
        }
    }
    
    if (currentLine) {
        lines.push(currentLine);
    }
    
    return lines.length > 0 ? lines : [text];
}

// 下载封面
function downloadCover() {
    const canvas = state.canvas;
    const link = document.createElement('a');
    const timestamp = new Date().getTime();
    link.download = `blog-cover-${timestamp}.png`;
    link.href = canvas.toDataURL('image/png');
    link.click();
}

// 重置所有设置
function resetAll() {
    // 重置自定义模式
    document.getElementById('bgImageInput').value = '';
    document.getElementById('titleText').value = '';
    document.getElementById('subtitleText').value = '';
    document.getElementById('textColor').value = '#ffffff';
    document.getElementById('titleSize').value = '48';
    document.getElementById('titleSizeValue').textContent = '48px';
    document.getElementById('subtitleSize').value = '24';
    document.getElementById('subtitleSizeValue').textContent = '24px';
    document.getElementById('titleBold').checked = false;
    document.getElementById('titleItalic').checked = false;
    document.getElementById('fontFamily').value = 'Arial, sans-serif';
    document.getElementById('overlayOpacity').value = '40';
    document.getElementById('overlayOpacityValue').textContent = '40%';
    document.getElementById('textPosition').value = 'center';
    document.getElementById('aspectRatio').value = '16:9';
    
    // 重置模板模式
    document.getElementById('templateTitleText').value = '';
    document.getElementById('templateSubtitleText').value = '';
    document.getElementById('templateAspectRatio').value = '16:9';
    document.getElementById('templateTitleSize').value = '48';
    document.getElementById('templateTitleSizeValue').textContent = '48px';
    document.getElementById('templateSubtitleSize').value = '24';
    document.getElementById('templateSubtitleSizeValue').textContent = '24px';
    document.getElementById('templateTitleBold').checked = true;
    document.getElementById('templateTitleItalic').checked = false;
    
    // 重置状态
    state.backgroundImage = null;
    state.aspectRatio = '16:9';
    state.currentTemplate = 'gradient1';
    
    // 重新选择第一个模板
    document.querySelectorAll('.template-item').forEach(i => i.classList.remove('selected'));
    document.querySelector('.template-item').classList.add('selected');
    
    // 重绘
    updateCanvasSize();
    drawCover();
}